<template>
	<view class="w-710 ml-20 pb-60">
		<!-- 顶部navbar -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }" mode="aspectFill">
		</image>
		<u-navbar title="我的待办" :autoBack="false" leftIcon=" " bgColor="transparent" :titleStyle="{ color: '#fff' }"
			safeAreaInsetTop placeholder></u-navbar>
		<image src="/static/icon_bj3.png" class="w-710 h-280 mgt" mode="aspectFil"></image>
		<!-- 搜索栏 -->
		<u-search placeholder="请输入搜索内容" v-model="form.instanceName" bgColor="#fff" @search="handleSearch"
			@clear="handleClear" @custom="handleSearch"></u-search>
		<!-- 列表 -->
		<!-- 审批类待办 -->
		<view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20 pb-20" v-for="(item, index) in list" :key="item.id">
			<view class="rowsb rowsm h-58">
				<view class="fs-30 fw-b">{{ item.instanceName }}</view>
				<view class="w-88 h-36 br-8 rowsc rowsm colfff fs-22" style="background: #FF8C34;">{{ item.status }}
				</view>
			</view>
			<view class="rows rowsm h-58">
				<view class="fs-28 fw-500 col888 label">任务节点</view>
				<view class="fs-28 fw-500 col888 mr-10 ml-10">:</view>
				<view class="">{{ item.stage }}</view>
			</view>
			<view class="rows rowsm h-58">
				<view class="fs-28 fw-500 col888 label">附件</view>
				<view class="fs-28 fw-500 col888 mr-10 ml-10">:</view>
				<view class="">{{ item.attach }}</view>
			</view>
			<view class="rows rowsm h-58">
				<view class="fs-28 fw-500 col888 label">发起人</view>
				<view class="fs-28 fw-500 col888 mr-10 ml-10">:</view>
				<view class="">{{ item.data.person || '暂无' }}</view>
			</view>
			<view class="rows rowsm h-58">
				<view class="fs-28 fw-500 col888 label">时间</view>
				<view class="fs-28 fw-500 col888 mr-10 ml-10">:</view>
				<view class="">{{ item.createdDate }}</view>
			</view>

			<view class="rowse rowsm h-58 pt-20" style="border-top: 1px solid #E5E7EB;">
				<view v-if="item.definitionKey === 'provinceMonitorTask' || item.definitionKey === 'byMonitorTask'"
					class="rowse rowsm">
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						@click="toDetail(item)">任务详情</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" v-if="userType == 1 && item.data.oldProductId != 6"
						@click="handleDispatch(item)">下发</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" v-if="(userType == 2 && item.data.productId == 3)"
						@click="handleDispatch(item)">下发</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="qianshou(item.id)"
						v-if="(userType == 2 && item.data.productId == 1)">签收</view>
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333"
						v-if="(userType == 1 && item.data.oldProductId != 6) || (userType == 2 && item.data.productId !== '1')"
						style="border: 1px solid #29a74d;margin-left: 20rpx;" @click="handleEdit(item)">编辑</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="qianshou(item.id, 1)"
						v-if="((userType == 3) && item.data.oldProductId == 1)">签收</view>

					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="qianshou(item.id, [])"
						v-if="userType == 4 && item.data.oldProductId == 1" style="margin-left: 10rpx;">签收</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="chouyang(item.id)"
						v-if="(userType == 4 && item.data.oldProductId == 2)">抽样单</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="banli(item.id, 3)"
						v-if="userType == 4 && item.data.oldProductId == 2" style="margin-left: 10rpx;">办理</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="chouyang(item.id, 1)"
						v-if="userType == 4 && item.data.oldProductId == 3" style="margin-left: 10rpx;">检测单</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="banli(item.id, 4)"
						v-if="userType == 4 && item.data.oldProductId == 3" style="margin-left: 10rpx;">办理</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="chouyang(item.id, 1, 5)"
						v-if="userType == 4 && item.data.oldProductId == 4" style="margin-left: 10rpx;">审核</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="chouyang(item.id, 1, 6)"
						v-if="userType == 4 && item.data.oldProductId == 5" style="margin-left: 10rpx;">批准</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" @click="chouyang(item.id, 1, 7)"
						v-if="userType == 1 && item.data.oldProductId == 6" style="margin-left: 10rpx;">公示</view>
				</view>

				<view
					v-if="!(item.taskDefinitionKey == 'institutionTask' || item.definitionKey == 'provinceMonitorTask' || item.definitionKey == 'byMonitorTask' || item.taskDefinitionKey == 'municipalTask' || item.taskDefinitionKey == 'countySamplingTask' || item.taskDefinitionKey == 'countyTask' || item.taskDefinitionKey == 'institutionSamplingTask' || item.taskDefinitionKey == 'institutionTestingTask')"
					style="display: flex;align-items: center;">
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						@click="viewTaskDetail(item)">任务详情
					</view>
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						v-if="item.signStatus !== true" @click="signTask(item.id)">签收</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32" v-if="isSpecialDefinition(item.definitionKey)"
						@click="toDetail(item)">审批
					</view>
					<!-- <view class="w-132 h-52 colfff bg rowsc rowsm br-32"
						v-if="isSpecialDefinition2(item.definitionKey)">下发
					</view> -->
					<view class="w-160 h-52 colfff bg rowsc rowsm br-32"
						v-if="item.claimed == true && item.taskDefinitionKey == 'inspection_org_process'"
						@click="assignFastDetectionTask(item)">指定快检员
					</view>
					<view class="w-160 h-52 colfff bg rowsc rowsm br-32 mr-20"
						v-if="item.claimed == true && item.taskDefinitionKey == 'quick_inspector_work'"
						@click="gokuaijianxiafa(item)">抽样单
					</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32"
						v-if="item.claimed == true && item.taskDefinitionKey == 'quick_inspector_work'" @click="xiafa(item)">下发
					</view>
					<view class="w-160 h-52 colfff bg rowsc rowsm br-32 mr-20"
						v-if="item.claimed == true && item.taskDefinitionKey == 'inspector_process'" @click="gokuaijianxiafa(item)">
						检测单
					</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32"
						v-if="item.claimed == true && item.taskDefinitionKey == 'inspector_process'" @click="xiafa(item)">下发
					</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32"
						v-if="item.claimed == true && item.taskDefinitionKey == 'approver_process'" @click="xiafa(item)">下发
					</view>
					<view class="w-132 h-52 colfff bg rowsc rowsm br-32"
						v-if="item.claimed == true && item.taskDefinitionKey == 'approval_process'" @click="pizhun(item)">批准
					</view>
				</view>
				<view
					v-if="item.taskDefinitionKey == 'institutionTask' || item.taskDefinitionKey === 'municipalTask' || item.taskDefinitionKey == 'countySamplingTask' || item.taskDefinitionKey == 'countyTask' || item.taskDefinitionKey == 'institutionSamplingTask' || item.taskDefinitionKey == 'institutionTestingTask'"
					style="display: flex;align-items: center;">
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						v-if="item.taskDefinitionKey !== 'institutionSamplingTask'" @click="showtcjcrw1(item.businessKey, index)">查看
					</view>
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						v-if="(item.status == 'CREATED' && !(item.taskDefinitionKey == 'institutionSamplingTask'))"
						@click="getclaim(item.id)">签收
					</view>
					<view class="w-132 h-52 rowsc rowsm br-32 mr-20 fs-26 col333" style="border: 1px solid #29a74d;"
						v-if="item.status == 'ASSIGNED'" @click="xiafa1(item.businessKey, index)">下发
					</view>
					<view style="border: 1px solid #29a74d;padding: 6rpx 16rpx;border-radius: 50rpx;"
						v-if="item.taskDefinitionKey == 'institutionSamplingTask'" @click="editcyd(item.data.processVariables.countyDept.receiveId)">编辑抽样单
					</view>
					<view style="border: 1px solid #29a74d;padding: 6rpx 16rpx;border-radius: 50rpx;"
						v-if="item.taskDefinitionKey == 'institutionSamplingTask'" @click="editjcd(item.data.processVariables.countyDept.receiveId)">编辑检测单
					</view>
				</view>
			</view>
		</view>
		<!-- 快检员选择弹窗 -->
		<u-popup :show="showPopup" mode="center" :border-radius="20" :closeable="true" @close="close">
			<view class="user-select-modal">
				<view class="modal-header">
					<view class="modal-title">选择快检员</view>
				</view>
				<view class="modal-content">
					<view class="user-list">
						<view v-for="(user, index) in userList" :key="user.userId" class="user-item" @click="toggleUser(index)">
							<view class="user-info">
								<view class="user-name">{{ user.userName || user.nickName || user.realName }}</view>
								<view class="user-dept" v-if="user.deptName">{{ user.deptName }}</view>
							</view>
							<view class="checkbox" :class="{ 'checked': user.selected }">
								<u-icon v-if="user.selected" name="checkmark" size="16" color="#fff"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<view class="btn-cancel" @click="cancel">取消</view>
					<view class="btn-confirm" @click="confirmSelection">确定({{ selectedCount }})</view>
				</view>
			</view>
		</u-popup>
		<!-- 加载更多 -->
		<view class="load-more" v-if="list.length > 0">
			<view v-if="loading" class="loading-text">
				<u-loading-icon mode="spinner" size="24" color="#999"></u-loading-icon>
				<text class="ml-10">加载中...</text>
			</view>
			<view v-else-if="!hasMore" class="no-more-text">
				没有更多数据了
			</view>
			<view v-else class="load-more-btn" @click="loadMore">
				加载更多
			</view>
		</view>

		<u-popup :show="showtcjcrw" @close="showtcjcrw=false" mode="center" round="10">
			<view class="zsjrw">
				<view class="sjrw">上级任务信息</view>
				<view class="sjrw1">
					<view class="sjrw2">
						<view>任务下发机构</view>
						<view class="sjrw3">{{trckform.inputDeptName ? trckform.inputDeptName : '-'}}</view>
					</view>
					<view class="sjrw2">
						<view>任务数量</view>
						<view class="sjrw3">{{shuliang}}</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 底部tabbar -->
		<CustomTabbar currentTab="daiban" />
	</view>
</template>

<script>
	import {
		rwlist,
		formDataShow,
		formDataSave,
		bdformDataShow,
		getTaskSignStatus,
		signTask,
		assignMonitorTask,
		checkMonitorTask,
		soilMonitorTaskdetail,
		claim,
		complete,
		soilMonitorTaskList
	} from '@/api/sylin/index.js'
	import {
		getFastDetectionTaskUsers,
		fastDetectionTaskSave,
		fastDetectionTaskSave2
	} from '@/api/kuaijian.js'
	export default {
		data() {
			return {
				shuliang: 0,
				trckform: {
					inputDeptName: '',

				},
				showtcjcrw: false,
				keyword: '',
				customNavbarHeight: null,
				list: [],
				showPopup: false,
				columns: [],
				form: {
					pageNum: 1,
					pageSize: 10,
					instanceName: ''
				},
				soilform: {
					pageNum: 1,
					pageSize: 10,
					definitionKey: 'soil_inspection_task'
				},
				loading: false,
				hasMore: true,
				userType: 1, // 用户类型，默认为1
				currentTaskId: null, // 当前操作的任务ID
				userList: [], // 快检员列表
				// 审批类待办
				specialDefinitions: [
					'outAcreage',
					'output',
					'courseware',
					'policyDepot',
					'brandBase',
					'skill',
					'activity',
					'monitorTask',
					'soil_inspection_main',
					'outputValue',
				],
				// 下发类待办
				specialDefinitions2: [
					'provinceMonitorTask',
					'byMonitorTask',
				],
				isshuaxin: 0
			}
		},
		computed: {
			navbarHeight() {
				// 如果设置了自定义高度，则使用自定义高度
				if (this.customNavbarHeight) {
					return this.customNavbarHeight;
				}
				// 否则自动计算：状态栏高度 + 导航栏高度
				const systemInfo = uni.getSystemInfoSync();
				// 将px转换为rpx (1px = 2rpx)
				const statusBarHeightRpx = systemInfo.statusBarHeight * 2;
				const navbarHeightRpx = 44 * 2; // 44px = 88rpx
				return statusBarHeightRpx + navbarHeightRpx;
			},
			// 选中的快检员数量
			selectedCount() {
				return this.userList.filter(user => user.selected).length;
			}
		},
		onShow() {
			if (this.isshuaxin) {
				this.refreshList()
				this.isshuaxin = 0
			}
			this.getsoilMonitorTaskList()
		},
		onLoad() {
			this.refreshList()
			this.userType = uni.getStorageSync('userType')
			this.getsoilMonitorTaskList()
		},
		methods: {
			// 土壤任务列表
			async getsoilMonitorTaskList() {
				try {
					console.log('开始获取土壤任务列表，参数:', this.soilform)
					console.log('当前用户类型:', this.userType)
					
					// 根据用户类型调整查询参数
					const queryParams = {
						...this.soilform,
						userType: this.userType
					}
					
					const res = await soilMonitorTaskList(queryParams)
					console.log('土壤任务列表接口返回:', res)
					
					// 检查数据结构并处理数据
					if (res && res.rows && res.rows.length > 0) {
						console.log('土壤任务列表数据:', res.rows)
						// 先移除已存在的土壤任务，避免重复
						this.list = this.list.filter(item => !item.isSoilTask)
						
						// 添加土壤任务标识
						const soilTasks = res.rows.map(item => ({
							...item,
							isSoilTask: true
						}))
						this.list.push(...soilTasks)
						console.log('合并后的列表:', this.list)
					} else if (res && res.data && res.data.list) {
						console.log('使用data.list字段:', res.data.list)
						this.list = this.list.filter(item => !item.isSoilTask)
						const soilTasks = res.data.list.map(item => ({
							...item,
							isSoilTask: true
						}))
						this.list.push(...soilTasks)
					} else {
						console.log('土壤任务列表为空或无数据，响应结构:', res)
					}
				} catch (error) {
					console.error('获取土壤任务列表失败:', error)
					uni.showToast({
						title: '获取土壤任务失败: ' + (error.message || error),
						icon: 'none',
						duration: 3000
					})
				}
			},
			editcyd(id) {
				uni.navigateTo({
					url: `/pages/trchouyangdan/trchouyangdan?id=${id}&taskId=${this.list[0].id}`
				})
			},
			editjcd(id) {
				uni.navigateTo({
					url: `/pages/mydaiban/soiljcd/soiljcd?id=${id}`
				})
			},
			async xiafa1(id, index) {
				const res1 = await this.$store.dispatch('GetInfo')
				console.log('获取用户信息成功，返回数据:', res1)
				this.shuliang = this.list[index].data.processVariables.municipalDeptList.filter(item => item
					.municipalDeptCandidates == res1.user.userName)[0].taskQuantity
				console.log('数量', this.shuliang)
				uni.navigateTo({
					url: `/subPkg/trjcbz/trjcrwAdd?id=${id}&num=${this.shuliang}`
				})
			},
			async getclaim(id) {
				const res = await claim(id)
				console.log(res)
				if (this.userType == 3 || this.userType == 4) {
					const res1 = await complete(id)
					uni.showToast({
						icon: 'none',
						title: '签收成功'
					})
					this.list = []
					this.form.pageNum = 1
					this.getList()
				}
				uni.showToast({
					icon: 'none',
					title: '签收成功'
				})
				this.list = []
				this.form.pageNum = 1
				this.getList()
			},
			async showtcjcrw1(id, index) {
				this.showtcjcrw = true
				const res = await soilMonitorTaskdetail(id)
				console.log(res);
				this.trckform.inputDeptName = res.data.inputDeptName
				console.log(this.trckform.inputDeptName);
				const res1 = await this.$store.dispatch('GetInfo')
				console.log('获取用户信息成功，返回数据:', res1)
				this.shuliang = this.list[index].data.processVariables.municipalDeptList.filter(item => item
					.municipalDeptCandidates == res1.user.userName)[0].taskQuantity
				console.log('数量', this.shuliang)

			},
			handleSearch() {
				this.list = []
				this.form.pageNum = 1
				this.getList()
			},
			xiafa(item) {
				uni.showModal({
					title: '提示',
					content: '确认下发吗?',
					success: async res => {
						if (res.confirm) {
							const res = await fastDetectionTaskSave(item.id, [])
							console.log(res)
							this.refreshList()
						}
					}
				})
			},
			pizhun(item) {
				uni.showModal({
					title: '提示',
					content: '确认批准吗?',
					success: async (modalRes) => {
						if (modalRes.confirm) {
							try {
								// 获取快检员列表
								const userRes = await getFastDetectionTaskUsers(item.data.institutionDeptId);
								console.log('快检员列表:', userRes);

								if (userRes.code === 200 && userRes.data && userRes.data.length > 0) {
									const userNames = userRes.data.map(user => user.userName || user.nickName || user.realName);
									// 调用批准接口
									const saveRes = await fastDetectionTaskSave2(item.id, userNames);
									console.log('批准结果:', saveRes);

									if (saveRes.code === 200) {
										uni.showToast({
											title: '批准成功',
											icon: 'success'
										});
										this.refreshList();
									} else {
										uni.showToast({
											title: saveRes.msg || '批准失败',
											icon: 'none'
										});
									}
								} else {
									uni.showToast({
										title: '暂无可用快检员',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('批准失败:', error);
								uni.showToast({
									title: '批准失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				})
			},
			// 查看任务详情（只读模式）
			viewTaskDetail(item) {
				// 将任务数据编码后传递
				const taskData = encodeURIComponent(JSON.stringify(item.data));
				// 根据taskDefinitionKey判断任务类型
				const taskType = item.taskDefinitionKey === 'quick_inspector_work' ? 'sampling' : 'detection';
				uni.navigateTo({
					url: `/pages/workbench/01task/kuaijianxiafa?id=${item.id}&taskData=${taskData}&taskType=${taskType}&readonly=true`
				})
			},

			gokuaijianxiafa(item) {
				// 将任务数据编码后传递
				const taskData = encodeURIComponent(JSON.stringify(item.data));
				// 根据taskDefinitionKey判断任务类型
				const taskType = item.taskDefinitionKey === 'quick_inspector_work' ? 'sampling' : 'detection';
				uni.navigateTo({
					url: `/pages/workbench/01task/kuaijianxiafa?id=${item.id}&taskData=${taskData}&taskType=${taskType}`
				})
			},
			// 指定快检员
			assignFastDetectionTask(item) {
				uni.showLoading({
					title: '加载中...'
				});

				// 使用institutionDeptId获取快检员列表，但保存任务ID用于下发
				getFastDetectionTaskUsers(item.data.institutionDeptId).then(res => {
					uni.hideLoading();
					console.log('快检员列表:', res);

					if (res.code === 200 && res.data && res.data.length > 0) {
						// 处理用户数据，添加选中状态
						this.userList = res.data.map(item => ({
							...item,
							selected: false
						}));
						this.currentTaskId = item.id; // 保存任务ID用于下发
						this.showPopup = true;
					} else {
						uni.showToast({
							title: '暂无可用快检员',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取快检员列表失败:', err);
					uni.showToast({
						title: '获取快检员列表失败',
						icon: 'none'
					});
				});
			},

			// 切换用户选中状态
			toggleUser(index) {
				this.userList[index].selected = !this.userList[index].selected;
			},

			// 确认选择
			confirmSelection() {
				const selectedUsers = this.userList.filter(user => user.selected);

				if (selectedUsers.length === 0) {
					uni.showToast({
						title: '请选择至少一个快检员',
						icon: 'none'
					});
					return;
				}

				// 显示选中的快检员信息
				const selectedNames = selectedUsers.map(user => user.userName || user.nickName || user.realName).join(',');

				this.assignTaskToUsers(this.currentTaskId, selectedUsers);

			},

			// 将任务分配给多个用户
			assignTaskToUsers(taskId, selectedUsers) {
				uni.showLoading({
					title: '下发中...'
				});

				// 准备下发数据 - 传递用户名数组
				const userNames = selectedUsers.map(user => user.userName || user.nickName || user.realName);

				// 调用下发接口
				fastDetectionTaskSave(taskId, userNames).then(res => {
					uni.hideLoading();
					console.log('下发结果:', res);

					if (res.code === 200) {
						uni.showToast({
							title: `已下发给${selectedUsers.length}位快检员`,
							icon: 'success'
						});
						this.showPopup = false;
						this.refreshList();
					} else {
						uni.showToast({
							title: res.msg || '下发失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('下发失败:', err);
					uni.showToast({
						title: '下发失败，请重试',
						icon: 'none'
					});
				});
			},
			cancel() {
				this.showPopup = false
			},
			close() {
				this.showPopup = false
			},
			banli(id, num) {
				this.isshuaxin = 1
				uni.showModal({
					title: '提示',
					content: '确认办理吗?',
					success: async res => {
						if (res.confirm) {
							const res = await checkMonitorTask(id, {
								str: num
							})
							console.log(res)
							uni.showToast({
								icon: 'none',
								title: '办理成功'
							})
							this.refreshList()
						}
					}
				})
			},
			chouyang(id, index, index1) {
				if (index1) this.isshuaxin = 1
				if (!index) {
					uni.navigateTo({
						url: `/pages/mydaiban/chouyangdan/chouyangdan?id=${id}`
					})
				} else if (!index1) {
					uni.navigateTo({
						url: `/pages/mydaiban/chouyangdan/chouyangdan?id=${id}&index=${index}`
					})
				} else {
					uni.navigateTo({
						url: `/pages/mydaiban/chouyangdan/chouyangdan?id=${id}&index=${index}&index1=${index1}`
					})
				}

			},
			// 编辑（示例：编辑同下发页）
			handleEdit(item) {
				this.isshuaxin = 1
				uni.navigateTo({
					url: `/pages/workbench/01task/monitor-submit?taskId=${item.id}&edit=1`
				})
			},
			qianshou(id, i) {
				if (i) {
					uni.showModal({
						title: '提示',
						content: '确认签收吗?',
						success: async res => {
							if (res.confirm) {
								const res = await assignMonitorTask(id, [])
								console.log(res)
								uni.showToast({
									icon: 'none',
									title: '签收成功'
								})
								this.refreshList()
							}
						}
					})
					return
				}
				uni.showModal({
					title: '提示',
					content: '确认签收吗?',
					success: async res => {
						if (res.confirm) {
							const res = await checkMonitorTask(id, {
								str: 11
							})
							console.log(res)
							uni.showToast({
								icon: 'none',
								title: '签收成功'
							})
							this.refreshList()
						}
					}
				})
			},
			// 下发（示例：跳转到监测下发页面）
			handleDispatch(item) {
				uni.showModal({
					title: '提示',
					content: '确认下发吗?',
					success: async res => {
						if (res.confirm) {
							const res = await assignMonitorTask(item.id, [])
							console.log(res)
							uni.showToast({
								icon: 'none',
								title: '下发成功'
							})
							this.refreshList()
						}
					}
				})
			},
			// 签收任务
			signTask(id) {
				// 确认弹窗
				uni.showModal({
					title: '提示',
					content: '确定签收吗？',
					success: (res) => {
						if (res.confirm) {
							signTask(id).then(res => {
								console.log('签收成功:', res)
								this.getTaskSignStatus(id)
								this.refreshList()
							})
						}
					}
				})
			},
			// 获取任务的签收状态
			getTaskSignStatus(id) {
				getTaskSignStatus(id).then(res => {
					this.list.forEach(item => {
						if (item.id == id) {
							item.signStatus = res.data
							console.log(item)
						}
					})
				})
			},
			// 获取任务列表
			getList(isRefresh = false) {
				if (this.loading) return;

				this.loading = true;

				// 如果是刷新，重置分页
				if (isRefresh) {
					this.form.pageNum = 1;
					this.list = [];
					this.hasMore = true;
				}

				rwlist(this.form).then(res => {
					const newList = res.rows.map(item => ({
						...item,
						data: item.data || {}, // 兜底空对象
						signStatus: item.signStatus // 兜底签收状态
					}));

					if (isRefresh) {
						this.list = newList;
					} else {
						this.list = [...this.list, ...newList];
					}

					// 判断是否还有更多数据
					this.hasMore = newList.length >= this.form.pageSize;

					// 获取签收状态
					this.list.forEach(item => {
						this.getTaskSignStatus(item.id)
					})
				}).catch(err => {
					console.error('获取列表失败:', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
				})
			},

			// 加载更多
			loadMore() {
				if (this.loading || !this.hasMore) return;

				this.form.pageNum++;
				this.getList();
			},

			// 刷新列表
			refreshList() {
				this.getList(true);
			},
			// 审批类待办
			isSpecialDefinition(definitionKey) {
				return this.specialDefinitions.includes(definitionKey)
			},
			// 下发类待办
			isSpecialDefinition2(definitionKey) {
				return this.specialDefinitions2.includes(definitionKey)
			},
			// 去审批
			toDetail(item) {
				if (item.definitionKey == 'outAcreage') { //面积上报11
					uni.navigateTo({
						url: `/subPkg/zzmjsb/zzmjsb?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'output') { //产量上报11
					uni.navigateTo({
						url: `/subPkg/zzmjsb/zzclsb?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'outputValue') { //产值上报11
					uni.navigateTo({
						url: `/subPkg/zzmjsb/zzczsb?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'policyDepot') { //政策法规上报11
					uni.navigateTo({
						url: `/subPkg/zzmjsb/cjzcfg?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'skill') { // 栽培技术审批11
					uni.navigateTo({
						url: `/subPkg/zzmjsb/cjzpjs?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'activity') { // 节庆活动审批11
					uni.navigateTo({
						url: `/pages/mydaiban/shenpi/activity?taskID=${item.id}`
					})
				} else if (item.definitionKey == 'courseware') { //云讲堂课件审批11
					console.log(item, "item")
					uni.navigateTo({
						url: `/pages/mydaiban/shenpi/courseware?taskID=${item.id}`
					})
				} else if (item.definitionKey === 'provinceMonitorTask' || item.definitionKey === 'byMonitorTask') {
					// 若为省级监测任务，跳转到监测下发/详情页
					uni.navigateTo({
						url: `/pages/workbench/01task/monitor-submit?taskId=${item.id}`
					})
					return
				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.zsjrw {
		padding: 20rpx;
		width: 500rpx;

		.sjrw {
			margin-bottom: 20rpx;
			font-size: 32rpx;
			font-weight: 700;
		}

		.sjrw1 {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.sjrw2 {
				text-align: center;
				width: 50%;
			}

			.sjrw3 {
				margin-top: 20rpx;
			}
		}
	}

	.mine-navbar-bg {
		position: fixed;
		top: 0;
		left: 0;
		width: 750rpx;
		z-index: 1;
	}

	.label {
		width: 120rpx;
		/* 固定宽度在 flex 布局下也不被压缩 */
		flex: 0 0 120rpx;
		text-align-last: justify;
	}

	.load-more {
		padding: 40rpx 0;
		text-align: center;
	}

	.loading-text {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 28rpx;
	}

	.load-more-btn {
		color: #007AFF;
		font-size: 28rpx;
		padding: 20rpx 40rpx;
		border: 1px solid #007AFF;
		border-radius: 8rpx;
		display: inline-block;
	}

	/* 快检员选择弹窗样式 */
	.user-select-modal {
		width: 600rpx;
		max-height: 80vh;
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.modal-header {
		padding: 40rpx 40rpx 20rpx;
		text-align: center;
		border-bottom: 1px solid #f0f0f0;
	}

	.modal-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.modal-content {
		max-height: 50vh;
		overflow-y: auto;
		padding: 20rpx 0;
	}

	.user-list {
		padding: 0 20rpx;
	}

	.user-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 20rpx;
		border-bottom: 1px solid #f5f5f5;
		transition: background-color 0.2s;
	}

	.user-item:active {
		background-color: #f8f8f8;
	}

	.user-item:last-child {
		border-bottom: none;
	}

	.user-info {
		flex: 1;
	}

	.user-name {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	.user-dept {
		font-size: 24rpx;
		color: #999;
	}

	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s;
	}

	.checkbox.checked {
		background-color: #007AFF;
		border-color: #007AFF;
	}

	.modal-footer {
		display: flex;
		padding: 20rpx 40rpx 40rpx;
		gap: 20rpx;
	}

	.btn-cancel {
		flex: 1;
		height: 80rpx;
		background: #f5f5f5;
		color: #666;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}

	.btn-confirm {
		flex: 1;
		height: 80rpx;
		background: #007AFF;
		color: #fff;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}
</style>